//
//  CustomTableView.m
//  SwipeTableView
//
//  Created by Roy lee on 16/4/1.
//  Copyright © 2016年 Roy lee. All rights reserved.
//

#import "CustomTableView.h"
#import "UIView+STFrame.h"
#import "STRefresh.h"
#import "SwipeTableView.h"
#import "aRCell.h"
#import "aRModel.h"
#import "aRquestModel.h"
#import "PlayViewController.h"
#import "MusicTool.h"
#import "LKActionSheetView.h"

NSString *const cpmStr = @"$$";

@interface CustomTableView ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDataSource , UIPickerViewDelegate>
@property (nonatomic, assign) NSInteger itemIndex;
@property (nonatomic, assign) NSInteger numberOfRows;

@property (nonatomic, strong) NSArray   *dataArr;
@property (nonatomic, strong) NSArray   *source;
@property (nonatomic, assign) NSInteger pickNum;
@end

@implementation CustomTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        self.tableFooterView = [UIView new];
        self.rowHeight  = 45;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self registerNib:aRNibLoad(@"aRCell") forCellReuseIdentifier:@"aRCell"];
        self.itemIndex = -1;
        _dataArr = @[].mutableCopy;
        self.header = [STRefreshHeader headerWithRefreshingBlock:^(STRefreshHeader *header) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadData];
                [header endRefreshing];
            });
        }];
    }
    return self;
}


//DATA
- (void)refreshWithData:(NSArray*)numberOfRows atIndex:(NSInteger)index {
    _numberOfRows = [numberOfRows count];
    _itemIndex = index;
    _dataArr = numberOfRows;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}


#pragma mark - UITableView M
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    aRModel *tempModel = self.dataArr[indexPath.row];
    aRCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aRCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString * title = nil;
    if (_itemIndex >= 0) {
    }else {
        title = [NSString stringWithFormat:@"第 %ld 行",indexPath.row];
    }
    
    __weak typeof(self) weakSelf = self;
    [cell.headimg sd_setImageWithURL:aRUrl(tempModel.pic) placeholderImage:aR_Image(@"star") options:0];
    cell.songName.text = tempModel.title;
    cell.artist.text = tempModel.author;
    cell.tagStr = tempModel.index;
    cell.urlStr = tempModel.url;
    cell.numLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    [cell setClickBack:^{
        if (_itemIndex == 4) {
            [aRquestModel request5SingUrl:tempModel.index Block:^(NSString *str,NSString *head) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = str;
                [UIView showloginTip:@"复制成功"];
            }];
        }else [weakSelf choosePickerView:tempModel];
        
    }];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_dataArr.count > 0) {
        if (_itemIndex == 4) {
            aRModel *tempModel = self.dataArr[indexPath.row];
            [aRquestModel request5SingUrl:tempModel.index Block:^(NSString *str,NSString *head) {
                MusicModel *mod = [MusicModel new];
                mod.singer = tempModel.author;
                mod.songName = tempModel.title;
                mod.fileName = str;
                mod.albumImage = head;
                self.cellBack(mod);
                [[MusicTool sharedMusicTool] setMusicList:@[mod]];
            }];
            return;
        }
        NSMutableArray *mutArr = @[].mutableCopy;
        for (NSInteger i = 0; i < self.dataArr.count; i++) {
            aRModel *tempModel = self.dataArr[i];
            MusicModel *mod = [MusicModel new];
            mod.singer = tempModel.author;
            mod.songName = tempModel.title;
            mod.fileName = tempModel.url;
            mod.albumImage = tempModel.pic;
            [mutArr addObject:mod];
            if (i == indexPath.row) {
                self.cellBack(mod);
            }
        }
        [[MusicTool sharedMusicTool] setMusicList:mutArr];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
#if !defined(ST_PULLTOREFRESH_HEADER_HEIGHT)
    STRefreshHeader * header = self.header;
    CGFloat orginY = - (header.st_height + self.swipeTableView.swipeHeaderView.st_height + self.swipeTableView.swipeHeaderBar.st_height);
    if (header.st_y != orginY) {
        header.st_y = orginY;
    }
#endif
}

-(void)copyMp3Url:(NSString*)str{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = str;
    [UIView showloginTip:@"复制成功"];
}

-(NSString*)add:(NSString*)URLstr
         type:(NSInteger)type{
    if(!URLstr) return nil;
    NSString *str = nil;
    switch (type) {
        case 0:str = @"标准音质";break;
        case 1:str = @"中等音质";break;
        case 2:str = @"高音质";break;
        case 3:str = @"无损";break;
    }
    return [NSString stringWithFormat:@"%@%@%@",URLstr,cpmStr,str];
}

#pragma mark---pickerDelegate
-(void)choosePickerView:(aRModel*)model{
    self.source = [NSArray arrayWithObjects:
                   [self add:model.url type:0],
                   [self add:model.mUrl type:1],
                   [self add:model.hUrl type:2],
                   [self add:model.wuSunUrl type:3],
                   nil];
    LKActionSheetView *as = [LKActionSheetView defaultActionSheetView];
    [as clear];
    as.headViewHeight = 44;
    as.title = @"选择音质进行复制";

    LKActionItem *cancel = [[LKActionItem alloc] initWithTitle: @"取消" onTouchBlock:^(LKActionItem *item) {
        [as hide];
    }];
    ((UILabel *)cancel.contentView).textColor = [UIColor redColor];
    [as addAction: cancel groupIndex: 0];
    [as addActionGroup];

    __weak typeof(self) weakSelf = self;
    LKActionItem *ok = [[LKActionItem alloc] initWithTitle: @"确认" onTouchBlock:^(LKActionItem *item) {
        NSArray *arr = [weakSelf.source[weakSelf.pickNum] componentsSeparatedByString:cpmStr];
        [UIPasteboard generalPasteboard].string = [arr firstObject];
        [UIView showloginTip:@"复制成功"];
        [as hide];
    }];
    [as addAction:ok  groupIndex: 0];
    [as addActionGroup];
    UIPickerView *picker = [[UIPickerView alloc] initWithFrame: CGRectMake(0, 0, aR_WIDTH, 160)];
    picker.dataSource = self;
    picker.delegate = self;
    [as addAction: [[LKActionItem alloc] initWithCustomView: picker height: 160 onTouchBlock: nil] groupIndex: 1];
    [as show];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.source.count;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.textColor = [UIColor darkGrayColor];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:14.0f]];
    }
    pickerLabel.text = [[self.source[row] componentsSeparatedByString:cpmStr] lastObject];
    return pickerLabel;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    _pickNum = row;
}



@end
